import { EventFieldNameMappingEnum } from '@model/enum/FieldMappingEnum.ts';
import { getTimestamp, formatAddress } from 'pub-bbx-utils';
import { expandField } from '@src/component/form/util'

/** 将form对象转成客户对象，用于提交表单 */
export function packToEvent(fields, form){
  let event = {
    id: form.id,
    attribute: {},
    subForms:[],
    // tick: form.tick || 0,
  };

  expandField(fields).forEach(field => {
    let {fieldName, isSystem} = field;
    let value = form[fieldName];

    if(fieldName === EventFieldNameMappingEnum.Customer){
      let customer = form.customer || [];
      // customer
      if(customer[0]){
        const { label, value } = customer[0]
        event.cusName = label
        event.cusId = value
      }

      // 客户联系人
      if(form.linkman && form.linkman[0]){
        let linkman = form.linkman[0];
        const { value, name, phone, email } = linkman;

        event.lmId = value
        event.lmName = name
        event.lmPhone = phone
        event.lmEmail = email
      }
      
      // 客户地址
      event.cusAddress = {};
      if(form.address && form.address[0]){
        let address = form.address[0];
        let taddress = {};

        taddress.id = address.value;
        taddress.country = address.country || '';
        taddress.province = address.province;
        taddress.city = address.city;
        taddress.dist = address.dist;
        taddress.latitude = address.latitude;
        taddress.longitude = address.longitude;
        taddress.address = address.address;

        event.cusAddress = address;
      } 

      // 产品
      event.products = [];
      if(form.product && form.product.length > 0){
        form.product.map(product => {
          event.products.push({
            id: product.id,
            name: product.name,
            serialNumber: product.serialNumber,
            type: product.type,
            customerId:product.customerId
          })
        })
      }
      
      return;
    }

    if (field.formType === EventFieldNameMappingEnum.Address && !field.isSystem && value) {
      
      let all = formatAddress(value,'');

      all && (value.all = all);
    }
    
    if (field.formType === EventFieldNameMappingEnum.Location) {
      value = {};
    }

    if (field.formType === EventFieldNameMappingEnum.PlanTime && value) {
      value = getTimestamp(value);
    }

    if (fieldName === EventFieldNameMappingEnum.Attachment && value) {
      // 拼附件和回执附件
      value = value.concat(form.receiptAttachment).filter(attachment => !!attachment);
    }

    if (field.formType == 'relationForm') {
      let subFormItemData = value.map(v=>{
        return{
          ...v,
          parentFieldName: field.fieldName
        }
      })
      event.subForms.push(...subFormItemData)
      return
    }

    isSystem == 0
      ? event.attribute[fieldName] = value
      : event[fieldName] = value;
  });

  return event;
}

/** 
 * @description 将工单对象转成form表单，用于初始化表单 
*/
export function packToForm(fields, data){
  // TODO: 临时注掉，如果有需要再修改
  // if (!data.id) return;
  
  let event = {
    id: data.id,
    eventNo: data.eventNo,
    templateName: data.templateName,
    ...data.attribute
  };

  let fieldValue = null

  fields.forEach(field => {
    let { fieldName, isSystem } = field;
    let value = data[fieldName];

    if(fieldName === EventFieldNameMappingEnum.Customer){
      // 初始化客户
      event.customer = [];
      if(data?.cusId) {
        event.customer = [{
          value: data.cusId,
          label: data.cusName,
          customerManager: value?.customerManager,
          synergies: value?.synergies
        }];
      }
      
      // 初始化联系人
      event.linkman = [];
      if(data.lmId) {
        event.linkman = [{
          value: data?.lmId,
          label: data?.lmName + data?.lmPhone,
          name: data?.lmName,
          phone: data?.lmPhone
        }];
      }

      // 初始化地址
      event.address = [];
      if (data?.cusAddress?.id) {
        event.address = [{
          value: data.cusAddress.id,
          label: (data.cusAddress?.province || '') + (data.cusAddress?.city || '') + (data.cusAddress?.dist || '') + (data.cusAddress?.address || ''),
          ...data.cusAddress
        }];
      }

      // 初始化产品
      data.products 
      && data.products.length 
      && data.products.map(item => {
        item.value = item.id;
        item.label = item.name;
      })
      event.product = data.products || [];

      return;
    }

    if (field.formType === EventFieldNameMappingEnum.PlanTime && value) {
      let { dateType = 'date' } = field.setting;
      value = dateType == 'date' ? value.substr(0, 10) : value;
    }

    if (fieldName === EventFieldNameMappingEnum.Attachment && value) {
      // 分离附件和回执附件
      if (value.length) {
        event.receiptAttachment = value.filter(img => img.receipt);
        value = value.filter(img => !img.receipt);
      }
    }

    // 字段值
    fieldValue = field.isSystem === 1 ? data[fieldName] : data?.attribute?.[fieldName]

    if(field.formType === 'relationForm'){
      let list = data.subForms || []
      fieldValue = []
      list.forEach(item => {
        if(item?.attribute?.parentFieldName && fieldName === item.attribute.parentFieldName){
          let obj = { ...item.attribute }
          fieldValue.push(obj)
        }
      })
    }

    if(isSystem == 1) {
      event[fieldName] = value
    }else{
      event[fieldName] = fieldValue
    }

  });

  return event;
}


